package com.ananjt.system.user.service.impl;

import com.ananjt.system.entity.SpMenu;
import com.ananjt.system.entity.SpUser;
import com.ananjt.system.user.mapper.SpUserMapper;
import com.ananjt.system.user.service.SpMenuService;
import com.ananjt.system.user.service.SpRoleService;
import com.ananjt.system.user.service.SpUserService;
import com.ananjt.system.vo.UserRoleVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sp.system.user.core.exception.TokenVerifyException;
import com.sp.system.user.core.utils.enums.PermissionEnum;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author chenanhai
 * @since 2020-03-16
 */
@Service
public class SpUserServiceImpl extends ServiceImpl<SpUserMapper, SpUser> implements SpUserService {

    private SpRoleService roleService;

    private SpMenuService menuService;


    /**
     * 菜单角色 权限
     * 1.FilterInvocationSecurityMetadataSource 先去判断请求路径 （可以参考sp-cus）
     * 2.使用 hasAnyRole 去判断权限标识 （本方法使用）
     *
     * @param loginName
     * @return
     */
    @Override
    public UserRoleVo getSystemUserByLoginName(String loginName) {

        SpUser spUser = new SpUser();
        if (StringUtils.isEmpty(loginName)) {
            throw new TokenVerifyException(PermissionEnum.USER_ERROR);
        }
        spUser.setLoginName(loginName);
        QueryWrapper<SpUser> userQueryWrapper = new QueryWrapper<>(spUser);
        SpUser user = baseMapper.selectOne(userQueryWrapper);

        UserRoleVo userRoleVo = new UserRoleVo();
        BeanUtils.copyProperties(user, userRoleVo);
        if (user != null) {
            // 设置 user 权限信息
            try {
                List<SpMenu> menuList = menuService.queryMenuByUserId(user);
                userRoleVo.setMenus(menuList);
            } catch (Exception e) {
                log.error("查询角色信息异常,{}", e);
            }
        } else {
            log.debug("SecurityUserDetails 用户信息查询为空 ！");
            throw new TokenVerifyException(PermissionEnum.USER_ERROR);
        }
        return userRoleVo;
    }

    @Autowired
    public void setMenuService(SpMenuService menuService) {
        this.menuService = menuService;
    }

    @Autowired
    public void setRoleService(SpRoleService roleService) {
        this.roleService = roleService;
    }
}
